import {FlatList, StyleSheet, View} from 'react-native';
import {
  Empty,
  GridOne,
  Header,
  ObserverText,
  ObserverView,
} from '../../components';
import {useTableReducer} from '../../hooks';
import {postWeekUpdateList, VipRankList} from '../../services';
import {useCallback, useEffect, useMemo, useState} from 'react';
import {dpw10, dpw12, dpw4, dpw40} from '../../constants';

const TodayUpdate = (props: any) => {
  const {navigation, route} = props;
  const {title, typeId} = route.params || {};
  const [{data, total, loading, pageIndex}, dispatch] = useTableReducer({
    total: 0,
    data: [],
    pageIndex: 1,
    pageSize: 10,
    loading: false,
  });
  const [day, setDay] = useState(-1);

  const orderDays = useMemo(() => {
    const dayMap = new Map([
      [0, 'week7'],
      [1, 'week1'],
      [2, 'week2'],
      [3, 'week3'],
      [4, 'week4'],
      [5, 'week5'],
      [6, 'week6'],
    ]);
    const list = [];
    const curD = new Date().getDay();
    list.push({id: -1, text: 'today'});
    for (let i = curD + 1; i < 7; i++) {
      list.push({id: i, text: dayMap.get(i)});
    }
    for (let i = 0; i < curD; i++) {
      list.push({id: i, text: dayMap.get(i)});
    }
    return list;
  }, []);

  const getData = useCallback(
    (idx: number, day: number, isMore?: boolean) => {
      if (day >= -1) {
        postWeekUpdateList({
          Type: typeId || 1,
          Days: day,
          PageIndex: idx,
          PageSize: 10,
        })
          .then((res: any) => {
            if (!Array.isArray(res?.Data)) {
              dispatch({type: 'error'});
            } else {
              dispatch({
                type: 'success',
                payload: {
                  data: isMore
                    ? (preD: any[]) => [...preD, ...res.Data]
                    : res?.Data,
                  total: res?.Count,
                  pageIndex: idx,
                },
              });
            }
          })
          .catch(() => {
            dispatch({type: 'error'});
          });
      }
    },
    [typeId, dispatch],
  );

  // 获取列表数据
  useEffect(() => {
    getData(1, day);
  }, [getData, day]);

  // 加载更多
  const onLoadMore = () => {
    if (!loading && typeof total === 'number' && total > (data || []).length) {
      getData(pageIndex + 1, day, true);
    }
  };

  const _randDataItem = ({item}: {item: {Id: string; list: any[]}}) => {
    return <GridOne list={item.list} typeId={typeId} navigation={navigation} />;
  };

  const changeDay = (id: number) => {
    if (id !== day) {
      setDay(id);
    }
  };

  const _randItem = ({item}: any) => {
    return (
      <ObserverText
        style={{paddingHorizontal: dpw12, paddingVertical: dpw4}}
        tKey={item.text}
        type="tab-title"
        isActive={day === item.id}
        onPress={() => changeDay(item.id)}
      />
    );
  };

  return (
    <ObserverView style={{flex: 1}} themeStyle={{backgroundColor: 'color_12'}}>
      <Header title="updatedToday" navigation={navigation} />
      <ObserverView style={styles.weeks}>
        <FlatList
          data={orderDays}
          horizontal={true}
          keyExtractor={item => `${item.id}`}
          renderItem={_randItem}
          showsHorizontalScrollIndicator={false}
        />
      </ObserverView>
      <View style={styles.con}>
        {Array.isArray(data) && data.length > 0 ? (
          <FlatList
            style={{paddingVertical: dpw12}}
            data={[{Id: 'today-update', list: data}]}
            renderItem={_randDataItem}
            keyExtractor={item => `${item.Id}`}
            onEndReachedThreshold={0.1}
            onEndReached={onLoadMore}
          />
        ) : (
          <Empty />
        )}
      </View>
    </ObserverView>
  );
};

const styles = StyleSheet.create({
  weeks: {
    // height: dpw40,
  },
  con: {
    flex: 1,
  },
});

export default TodayUpdate;
